package mz.matafe.bolao

/**
 * Domain Class for a Group.
 *
 * <p>Represents a group. Eg.: (Grupo A, Grupo B)
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class Group implements Comparable{

    //services
    def authenticateService

    //properties
    String name
    Date dateCreated
    Date lastUpdated
    User createdBy
    User updatedBy
    boolean active = true
    Cup cup

    static hasMany = [teams : Team]

    static belongsTo = [Cup]

    static constraints = {
        name(unique:'cup', blank:false, maxSize:1)
        cup(nullable: true)
        dateCreated()
        lastUpdated()
        createdBy(nullable:true)
        updatedBy(nullable:true)
        active()
    }

    static mapping = {
        table 'WC_GROUP'
        teams sort:'name'
        createdBy column: 'CREATED_BY'
        updatedBy column: 'UPDATED_BY'
    }

    def beforeInsert = {
        log.info "Before insert a Group"
        def loggedUser = authenticateService.userDomain()
        this.createdBy = this.createdBy ?: loggedUser
        this.updatedBy = updatedBy ?: loggedUser
    }

    def beforeUpdate = {
        log.info "Updating Group ${id} "
        this.updatedBy = authenticateService.userDomain()
    }

    def afterInsert = {
        log.info "Group ${id} inserted by ${createdBy}"
    }

    def afterUpdate = {
        log.info "Group ${id} updated by ${updatedBy}"
    }

    String toString(){
         "${this.class.name}:id[$id];name[$name]"
    }

    int compareTo(Object o){
        this.id.compareTo(((Group)o).id)
    }

}